// @ts-nocheck
import { getCurrentInstance } from 'vue'
import type { Designer} from './type'
import { cloneDeep, isFunction } from 'lodash';
import * as utils from '/@/utils/index'
import { allWidgets } from './widget-panel/widgetsConfig'
import { useMessage } from '/@/hooks/web/useMessage'
import { globalMapper } from './widget-panel/mapperConfig'
const { createMessage } = useMessage()

/**
 * 预览Json或者预览时候会将指定的key, 放到 导出的JSON根节点中
 */
const globalExtractKeys = [ 'globalConfig', 'terminalType' ]

export function createDesigner() : Designer {
  return {
    // 终端类型
    terminalType: 'pc',
    // 表单item配置
    formItemConfig: {},
    globalConfig: {
      cssCode: '',
      layoutType: 'horizontal', // 布局类型
      labelStyle: {
        width: '100px',
        textAlign: 'right'
      },
      labelCol: {
        // xs: '100px', // <576px
        // xl: '100px', // ≥1200px
      },
      wrapperCol: { }
    },
    selectedWidgetName: '',
    selectedId: undefined,
    selectedWidget: undefined,

    widgetList: [],

    getFieldWidgetByType(typeName) {
      let foundWidget = null
      allWidgets.forEach(widget => {
        if (widget.type && (widget.type === typeName)) {
          foundWidget = widget
        }
      })

      return foundWidget
    },

    hasWidgetConfig(widget, propName) {
      let originalWidget = null
      originalWidget = this.getFieldWidgetByType(widget.type)
      // console.log('---------------', propName, originalWidget)
      if (!originalWidget || !originalWidget.props) {
        return false
      }

      return Object.keys(originalWidget.props).indexOf(propName) > -1
    },

    hasFormConfig(propName) {
      let originalWidget = null
      if (!this.globalConfig) {
        return false
      }

      return Object.keys(this.globalConfig).indexOf(propName) > -1
    },

    copyNewFieldWidget(origin) {
      let newWidget = cloneDeep(origin)
      let tempId = utils.buildShortId()
      newWidget.id = newWidget.type.replace(/-/g, '') + tempId
      newWidget.props.formItemName = newWidget.type + tempId
      // delete newWidget.displayName
      return newWidget
    },
    
    setSelected(selected) {
      if (!selected) {
        this.clearSelected()
        return
      }
      this.selectedWidget = selected
      if (!!selected.id) {
        this.selectedId = selected.id
        this.selectedWidgetName = selected.props.formItemName
      }
    },
    clearSelected() {
      this.selectedId = null
      this.selectedWidgetName = null
      this.selectedWidget = null
    },

    changeTerminalType(newType) {
      this.terminalType = newType
    },

    clearDesigner() {
      this.widgetList = []
      this.clearSelected()
    },

    emitHistoryChange() {

    },

    loadJson(importJson) {
      try {
        let importObj = JSON.parse(importJson)
        //console.log('test import', this.importTemplate)
        if (!importObj || !importObj.globalConfig || !importObj.widgetList) {
          throw new Error('数据格式错误')
        }
        this.doLoadJson(importObj)
        this.emitHistoryChange()
      } catch (ex) {
        console.error(ex)
        createMessage.error(ex + '')
      }
    },

    doLoadJson(jsonData) {
      let modifiedFlag = false

      if (!!jsonData && !!jsonData.widgetList) {
        // this.formWidget.clearWidgetRefList()
        this.widgetList = jsonData.widgetList
        modifiedFlag = true
      }
      if (!!jsonData && !!jsonData.globalConfig) {
        utils.overwriteObj(this.globalConfig, jsonData.globalConfig)  /* 用=赋值，会导致inject依赖注入的globalConfig属性变成非响应式 */
        modifiedFlag = true
      }

      if (modifiedFlag) {
        // this.emitEvent('form-json-imported', [])  // 通知其他组件
      }
      return modifiedFlag
    },

    genExportJson(isMapper = true) {
      const that = this
      let widgetList : any = cloneDeep(this.widgetList)
      const globalConfig : any = {}
      globalExtractKeys?.filter(key => !!that[key]).forEach(key => {
        const value = cloneDeep(that[key])
        globalConfig[key] = value
      })


      const newWidgetList : any = []
      widgetList.forEach(widget => {
        const newWidget = { ...widget }
        const props = newWidget.props
        for (const key in props) {
            // 删除空值
          if ( typeof props[key] !== 'boolean' && !props[key]) {
            delete props[key]
            continue
          }
        }
        delete newWidget['icon']
        delete newWidget['settingForm']
        delete props['value']
        newWidgetList.push(newWidget)
      })

      return { 
        widgetList: newWidgetList,
        ...globalConfig
      }

      // const newWidgetList : any = []
      // widgetList.forEach(widget => {
      //   const newWidget = { ...widget }
      //   const props = newWidget.props
      //   delete props['value']
      //   for (const key in props) {
      //       // 删除空值
      //     if ( typeof props[key] !== 'boolean' && !props[key]) {
      //       delete props[key]
      //       continue
      //     }
      //   }

      //   // 处理字段映射
      //   const mappers : any[] = newWidget.mappers || []
      //   mappers.filter(e => e.key && e.mKey).forEach(mapper => {
      //     this.mapperField(mapper, newWidget)
      //   })
      //   delete newWidget['mappers']
      //   newWidgetList.push(newWidget)
      // })

      // // 全局配置映射
      // globalMapper.forEach(mapper => this.mapperField(mapper, globalConfig))

      // return { widgetList: newWidgetList, ...globalConfig }
    },

  }
}